<template>
  <component
    :is="component"
    v-bind="{ ...props, ...upload, handlePreview }"
  ></component>
  <a-image-preview-group :preview="preview">
    <a-image
      v-for="item in upload.state.fileList"
      style="display: none"
      :key="item.fileId"
      :src="item.url"
    ></a-image>
  </a-image-preview-group>
</template>
<script lang="ts" setup>
import { useUpload } from "@/hook/useUpload";
import { computed, reactive, watch } from "vue";
import type { CustomUploadProps } from "./typing";
import type { Options } from "@/hook/useUpload/typing";
import UploadDialog from "./components/upload-dialog.vue";
import UploadPreview from "./components/upload-preview.vue";
const component = computed(() => {
  if (props.type == "input") {
    return "UploadInput";
  } else if (props.type == "button") {
    return "UploadButton";
  } else if (props.type == "preview" && props.accept == "image/*") {
    return UploadPreview;
  } else {
    return UploadDialog;
  }
});
const props = withDefaults(defineProps<CustomUploadProps>(), {
  type: "dialog",
  maxFileSize: 1024 * 1024,
  maxFileNums: 9,
  width: 64,
  height: 64,
});
const emit = defineEmits(["update:value"]);
const options = reactive<Options>({
  fileHeaderId: props.value,
  accept: props.accept,
  maxFileNums: props.maxFileNums,
  maxFileSize: props.maxFileSize,
  chunkSize: 1024 * 5,
  multiple: props.multiple,
  onEmit: (fileHeaderId) => emit("update:value", fileHeaderId),
});
const upload = useUpload(options);
/**文件预览 */
const onVisibleChange = (bool: boolean) => {
  preview.visible = bool;
};
const preview = reactive({
  visible: false,
  onVisibleChange,
  current: 0,
});
const handlePreview = (current: number) => {
  preview.current = current;
  preview.onVisibleChange(true);
};
watch(
  () => props.value,
  (value) => {
    options.fileHeaderId = value;
  }
);
</script>
